﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace GSQ.BusinessEntities
{
    [Serializable()]
    public abstract class EntityBase : INotifyPropertyChanged
    {
        private List<BrokenRule> brokenRules = new List<BrokenRule>();

        public List<BrokenRule> BrokenRules
        {
            get { return brokenRules; }
            set { brokenRules = value; }
        }

        public bool IsValid()
        {
            this.brokenRules = new List<BrokenRule>();
            ValidationContext context = new ValidationContext(this, null, null);
            IList<ValidationResult> errors = new List<ValidationResult>();

            if (!Validator.TryValidateObject(this, context, errors, true))
            {
                foreach (ValidationResult result in errors)
                {
                    brokenRules.Add(new BrokenRule
                            {
                               Message = result.ErrorMessage,
                               PropertyName = result.MemberNames.ElementAt(0).ToString()
                            });
                }
            }
            if (errors.Count == 0)
                return true;
            else
                return false;

        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
